/*
 * Copyright 2021 ABSA Group Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package za.co.absa.spline.harvester.dispatcher

import org.apache.commons.configuration.Configuration
import org.apache.spark.internal.Logging
import za.co.absa.commons.EnumUtils.EnumOps
import za.co.absa.commons.config.ConfigurationImplicits._
import za.co.absa.commons.reflect.EnumerationMacros
import za.co.absa.spline.harvester.dispatcher.LoggingLineageDispatcher.{LevelKey, LevelLogger, LogFn}

class LoggingLineageDispatcher(logFn: LogFn)
  extends AbstractJsonLineageDispatcher {

  def this(conf: Configuration) = this(
    logFn = LevelLogger.valueOf(conf.getRequiredString(LevelKey)).logFn
  )

  override def name = "Logging"

  override protected def send(json: String): Unit = logFn(json)

}

object LoggingLineageDispatcher extends Logging {
  private val LevelKey = "level"

  type LogFn = (=> String) => Unit

  sealed abstract class LevelLogger(val rank: Int, val logFn: LogFn)

  object LevelLogger extends EnumOps[LevelLogger] {

    object Error extends LevelLogger(0, logError)

    object Warn extends LevelLogger(1, logWarning)

    object Info extends LevelLogger(2, logInfo)

    object Debug extends LevelLogger(3, logDebug)

    object Trace extends LevelLogger(4, logTrace)

    protected val values: Seq[LevelLogger] = EnumerationMacros.sealedInstancesOf[LevelLogger].toSeq.sortBy(_.rank)
  }

}


